package cn.xi.controller;


import cn.xi.checkItem.OrderService;
import cn.xi.constant.MessageConstant;
import cn.xi.constant.RedisMessageConstant;
import cn.xi.entity.Result;
import cn.xi.pojo.Order;
import cn.xi.utils.ValidateCodeUtils;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import java.util.Date;
import java.util.Map;

@RestController
@RequestMapping("/validateCode")
public class OrderController {

    @Reference
    private OrderService orderService;

    @Autowired
    private JedisPool jedisPool;

    @RequestMapping("/send4Order")
    public Result send4Order(String telephone) {
        try {
            Integer integer = ValidateCodeUtils.generateValidateCode(6);
            jedisPool.getResource().setex(telephone + RedisMessageConstant.SENDTYPE_ORDER, 300, integer.toString());
//            SMSUtils.sendShortMessage(SMSUtils.VALIDATE_CODE, telephone, integer.toString());
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.SEND_VALIDATECODE_FAIL);
        }
        return new Result(true, MessageConstant.SEND_VALIDATECODE_SUCCESS);
    }

    @RequestMapping("/send4Login")
    public Result send4Login(String telephone) {
        try {
            Integer integer = ValidateCodeUtils.generateValidateCode(6);
            jedisPool.getResource().setex(telephone + RedisMessageConstant.SENDTYPE_LOGIN, 300, integer.toString());
//            SMSUtils.sendShortMessage(SMSUtils.VALIDATE_CODE, telephone, integer.toString());
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.SEND_VALIDATECODE_FAIL);
        }
        return new Result(true, MessageConstant.SEND_VALIDATECODE_SUCCESS);
    }

    @RequestMapping("/submit")
    public Result submit(@RequestBody Map map) {
        Result add =new Result(false,MessageConstant.ORDERSETTING_FAIL);
        try {
            String validateCode = (String) map.get("validateCode");
            String telephone = (String) map.get("telephone");
            String ss = telephone + RedisMessageConstant.SENDTYPE_ORDER;
            String s = jedisPool.getResource().get(ss);
            if (s.equals(validateCode)) {
                map.put("orderType", Order.ORDERTYPE_WEIXIN);
                 add = orderService.add(map);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return add;
        }
        return add;
    }

    @RequestMapping("/findById")
    public Result findById(Integer id){
        Order byId = orderService.findById(id);
        return new Result(true,"",byId);
    }
}
